package userlogic

import (
	"context"

	configModel "gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/dao/model/config"
	"gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/dao/model/user"
	"gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/dao/schema/config"

	"gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/assets-rpc/rpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserWalletLogLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserWalletLogLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserWalletLogLogic {
	return &UserWalletLogLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// UserWalletLog 获取钱包日志
func (l *UserWalletLogLogic) UserWalletLog(req *rpc.UserWalletLogRequest) (*rpc.UserWalletLogResponse, error) {
	resp := &rpc.UserWalletLogResponse{
		Meta: &rpc.UserWalletLogResponse_Meta{
			Page:     req.Page,
			PageSize: req.PageSize,
		},
	}

	// NewInoutModel
	inoutModel := configModel.NewInoutModel(l.ctx, l.svcCtx.Db)
	inoutList, _ := inoutModel.All()
	inoutModelMap := make(map[int64]config.ConfigInoutType)
	for _, inout := range inoutList {
		inoutModelMap[inout.TypeId] = inout
	}

	// 初始化模型
	walletLogModel := user.NewWalletLogModel(l.ctx, l.svcCtx.Db)
	// 获取用户余额
	models, total, err := walletLogModel.List(req)
	if err != nil {
		return nil, err
	}
	// 总条数
	resp.Meta.Total = total
	// 数据映射
	n := len(models)
	resp.Data = make([]*rpc.UserWalletLogResponse_Data, 0, n)
	for i := 0; i < n; i++ {
		data := &rpc.UserWalletLogResponse_Data{
			Id:           models[i].ID,
			TypeId:       models[i].TypeID,
			TypeName:     inoutModelMap[models[i].TypeID].Name,
			Amount:       models[i].Amount,
			BalanceStart: models[i].BalanceStart,
			BalanceEnd:   models[i].BalanceEnd,
			CreatedAt:    models[i].CreatedAt,
			OperateId:    models[i].OperatorId,
			TransferType: int32(models[i].TransferType),
			Description:  models[i].Description,
			UserId:       models[i].UserId,
			Remark:       inoutModelMap[models[i].TypeID].Remark,
		}

		if name1, ok := inoutModelMap[models[i].TypeID]; ok {
			data.TypeName = name1.Name
		}

		resp.Data = append(resp.Data, data)
	}

	return resp, nil
}
